<?php

$thisPage = "popup_logoupload";

TemplateHelper::uselayout("popup");

addDataService("upload");
addHtmlService("upload");

$buttons = array();
$buttons[] = TemplateHelper::addButton("Open browser", "openFileBrowser('logofile')");
$buttons[] = TemplateHelper::addButton("Upload", "startUpload(this)");
$buttons[] = TemplateHelper::addButton("Close window", "closePopup()");

$popupId = getRequestParameter("popup_id");
$fileId = getRequestParameter("file_id");
$needThumbnail = getRequestParameter("needThumbnail");
$chkWidth = getrequestParameter("chk_width", 728);
$chkHeight = getRequestParameter("chk_height", 210);
$chkMinWidth = getRequestParameter("chk_minwidth");
$chkMinHeight = getRequestParameter("chk_minheight");

if ($needThumbnail) {
    $chkWidth = "";
    $chkHeight = "";
}

function executeService($serviceName, $params) {
    Log::debug("service name: $serviceName");
    if ($serviceName == "upload") {
        return execute_upload($params);
    }
}

function createThumbnail($file, $ext) {
    $thumbWidth = 105;
    $thumbHeight = 105;
    $content = "";

    Log::debug("file extension=$ext");
    if ($ext == "jpg") {
        $img = imagecreatefromjpeg($file);
        $width = imagesx( $img );
        $height = imagesy( $img );
        $new_width = $thumbWidth;
        $new_height = floor( $height * ( $thumbWidth / $width ) );
        $tmp_img = imagecreatetruecolor( $new_width, $new_height );
        imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
        ob_start();
        imagejpeg( $tmp_img );
        $content = ob_get_contents();
        ob_end_clean();
    } else if ($ext == "png") {
        $img = imagecreatefrompng($file);
        $width = imagesx( $img );
        $height = imagesy( $img );
        $new_width = $thumbWidth;
        $new_height = floor( $height * ( $thumbWidth / $width ) );
        $tmp_img = imagecreatetruecolor( $new_width, $new_height );
        imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
        ob_start();
        imagejpeg( $tmp_img );
        $content = ob_get_contents();
        ob_end_clean();
    } else if ($ext == "bmp") {
        $img = imagecreatefromwbmp($file);
        $width = imagesx( $img );
        $height = imagesy( $img );
        $new_width = $thumbWidth;
        $new_height = floor( $height * ( $thumbWidth / $width ) );
        $tmp_img = imagecreatetruecolor( $new_width, $new_height );
        imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
        ob_start();
        imagejpeg( $tmp_img );
        $content = ob_get_contents();
        ob_end_clean();
    } else if ($ext == "gif") {
        $img = imagecreatefromgif($file);
        $width = imagesx( $img );
        $height = imagesy( $img );
        $new_width = $thumbWidth;
        $new_height = floor( $height * ( $thumbWidth / $width ) );
        $tmp_img = imagecreatetruecolor( $new_width, $new_height );
        imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
        ob_start();
        imagejpeg( $tmp_img );
        $content = ob_get_contents();
        ob_end_clean();
    }
    return addslashes($content);
}

function execute_upload($params) {
    global $chkWidth;
    global $chkHeight;
    global $chkMinWidth;
    global $chkMinHeight;
    global $needThumbnail;

    Log::info("Executing service: upload");
    $chk = true;
    $needCrop = false;

    if ($chkWidth == "105" && $chkHeight == "105") {
        $chk = true;
        $imgdata = getimagesize($_FILES['logofile']['tmp_name']);
        if ($imgdata[0] > intval($chkWidth, 10) || $imgdata[1] > intval($chkHeight, 10)) {
            $needCrop = true;
        }
    } else if ($chkMinWidth != "") {
        $imgdata = getimagesize($_FILES['logofile']['tmp_name']);
        if ($imgdata[0] < intval($chkMinWidth, 10) || $imgdata[1] < intval($chkMinHeight, 10) || $imgdata[0] > intval($chkWidth, 10) || $imgdata[1] > intval($chkHeight, 10)) {
            $chk = false;
            setPopupCloseCallback("displayError", array(
                txt => "$tmp Uploaded file does not match the size requirements! (detected size is " . $imgdata[0] . "x".$imgdata[1] . ")",
            ));
        }
    } else if ($chkWidth != "") {
        $imgdata = getimagesize($_FILES['logofile']['tmp_name']);
        if ($imgdata[0] != intval($chkWidth, 10) || $imgdata[1] != intval($chkHeight, 10)) {
            $chk = false;
            setPopupCloseCallback("displayError", array(
                txt => "$tmp Uploaded file does not match the size requirements! (detected size is " . $imgdata[0] . "x".$imgdata[1] . ")",
            ));
        }
    }
    $cmps = explode(".", $_FILES['logofile']['name']);
    $ext = $cmps[count($cmps)-1];
    $thumb = createThumbnail($_FILES['logofile']['tmp_name'], $ext);
    if ($needThumbnail) {
    }
    if ($chk) {
        $fh = fopen($_FILES['logofile']['tmp_name'], "r");
        $content = addslashes(fread($fh, filesize($_FILES['logofile']['tmp_name'])));
        fclose($fh);

        $imgdata = getimagesize($_FILES['logofile']['tmp_name']);
        if ($needCrop) {
            $top = ceil(($imgdata[1]-105)/2);
            $left = ceil(($imgdata[0]-105)/2);
            $canvas = imagecreatetruecolor(105, 105);
            $image = imagecreatefrompng($_FILES['logofile']['tmp_name']);
            imagecopy($canvas, $image, 0, 0, $left, $top, 105, 105);
            ob_start();
            imagejpeg($canvas, NULL, 100);
            $content = addslashes(ob_get_contents());
            ob_end_clean();
        }
        Database::loadModel("files");
        if (isset($params['file_id'])) {
            Database::update(array(
                file_id => $params['file_id'],
                filename => $_FILES['logofile']['name'],
                owner => $_SESSION['userdata']['user_id'],
                content => $content,
                filetype => $_FILES['logofile']['type'],
                thumbnail_content => $thumb,
            ));
        } else {
            $id = Database::addNew(array(
                filename => $_FILES['logofile']['name'],
                owner => $_SESSION['userdata']['user_id'],
                content => $content,
                filetype => $_FILES['logofile']['type'],
                thumbnail_content => $thumb,
            ));
        }
        addPopupResult("logofileid", $id);
        setPopupCloseCallback("doAfterUpload", array(
            popupId => $params['popup_id'],
        ));
    }
    Log::info("Finishing service: upload");
    return generatePopupResult();
}


function buildLayout(&$smarty) {
    global $thisPage;
    global $buttons;
    global $popupId;
    global $fileId;
    global $chkWidth;
    global $chkHeight;
    global $chkMinWidth;
    global $chkMinHeight;

    $smarty->assign("popup_id", $popupId);
    $smarty->assign("file_id", $fileId);
    $smarty->assign("chk_width", $chkWidth);
    $smarty->assign("chk_height", $chkHeight);
    $smarty->assign("chk_minheight", $chkMinHeight);
    $smarty->assign("chk_minwidth", $chkMinWidth);
    $smarty->assign("content", $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "logoupload")));
    $smarty->assign("buttons", $buttons);
}

function getPageHeader() {
    return TemplateHelper::getDefaultPageHeader();
}

function getPageFooter() {
    return TemplateHelper::getDefaultPageFooter();
}

?>
